#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
质量管理系统 - Quality Management System

功能包括：
- 质量检验流程管理
- 不合格品处理流程
- 质量数据统计分析
- 质量改进建议系统
"""

import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple
import json
import logging
from dataclasses import dataclass, asdict
from enum import Enum
import uuid
from collections import defaultdict
import statistics

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class InspectionType(Enum):
    """检验类型枚举"""
    INCOMING = "incoming"        # 来料检验
    IN_PROCESS = "in_process"    # 过程检验
    FINAL = "final"             # 最终检验
    OUTGOING = "outgoing"       # 出货检验
    AUDIT = "audit"             # 审核检验

class InspectionResult(Enum):
    """检验结果枚举"""
    PASS = "pass"               # 合格
    FAIL = "fail"               # 不合格
    CONDITIONAL_PASS = "conditional_pass"  # 有条件合格
    PENDING = "pending"         # 待检
    REWORK = "rework"           # 返工

class DefectSeverity(Enum):
    """缺陷严重程度枚举"""
    CRITICAL = "critical"       # 严重
    MAJOR = "major"             # 主要
    MINOR = "minor"             # 次要
    COSMETIC = "cosmetic"       # 外观

class NCRStatus(Enum):
    """不合格品报告状态枚举"""
    OPEN = "open"               # 开启
    INVESTIGATING = "investigating"  # 调查中
    CORRECTIVE_ACTION = "corrective_action"  # 纠正措施中
    CLOSED = "closed"           # 关闭
    CANCELLED = "cancelled"     # 取消

class CAPAStatus(Enum):
    """纠正和预防措施状态枚举"""
    INITIATED = "initiated"     # 已启动
    PLANNING = "planning"       # 计划中
    IMPLEMENTING = "implementing"  # 实施中
    VERIFYING = "verifying"     # 验证中
    COMPLETED = "completed"     # 完成
    CANCELLED = "cancelled"     # 取消

@dataclass
class QualityStandard:
    """质量标准"""
    standard_id: str
    name: str
    category: str
    description: str
    acceptance_criteria: Dict[str, str]  # 验收标准
    test_methods: List[str]  # 测试方法
    sampling_plan: Dict[str, str]  # 抽样计划
    is_active: bool = True
    created_date: datetime = None
    
    def __post_init__(self):
        if self.created_date is None:
            self.created_date = datetime.now()

@dataclass
class InspectionPlan:
    """检验计划"""
    plan_id: str
    product_id: str
    inspection_type: str
    standard_id: str
    frequency: str  # 检验频率
    sample_size: int
    inspector_requirements: List[str]  # 检验员要求
    equipment_required: List[str]  # 所需设备
    is_active: bool = True
    created_date: datetime = None
    
    def __post_init__(self):
        if self.created_date is None:
            self.created_date = datetime.now()

@dataclass
class InspectionRecord:
    """检验记录"""
    record_id: str
    plan_id: str
    batch_id: str
    product_id: str
    inspection_type: str
    inspector_id: str
    inspection_date: datetime
    sample_size: int
    tested_quantity: int
    result: str = InspectionResult.PENDING.value
    measurements: Dict[str, float] = None  # 测量数据
    defects: List[Dict] = None  # 缺陷记录
    notes: str = ""
    completion_date: Optional[datetime] = None
    
    def __post_init__(self):
        if self.measurements is None:
            self.measurements = {}
        if self.defects is None:
            self.defects = []

@dataclass
class DefectRecord:
    """缺陷记录"""
    defect_id: str
    inspection_record_id: str
    defect_type: str
    defect_description: str
    severity: str
    quantity: int
    location: str = ""
    root_cause: str = ""
    corrective_action: str = ""
    created_date: datetime = None
    
    def __post_init__(self):
        if self.created_date is None:
            self.created_date = datetime.now()

@dataclass
class NCR:
    """不合格品报告 (Non-Conformance Report)"""
    ncr_id: str
    inspection_record_id: str
    product_id: str
    batch_id: str
    description: str
    severity: str
    quantity_affected: int
    status: str = NCRStatus.OPEN.value
    reported_by: str = ""
    assigned_to: str = ""
    root_cause_analysis: str = ""
    immediate_action: str = ""
    containment_action: str = ""
    created_date: datetime = None
    closed_date: Optional[datetime] = None
    
    def __post_init__(self):
        if self.created_date is None:
            self.created_date = datetime.now()

@dataclass
class CAPA:
    """纠正和预防措施 (Corrective and Preventive Action)"""
    capa_id: str
    ncr_id: str
    title: str
    description: str
    root_cause: str
    corrective_actions: List[str]
    preventive_actions: List[str]
    responsible_person: str
    target_completion_date: datetime
    status: str = CAPAStatus.INITIATED.value
    effectiveness_verification: str = ""
    actual_completion_date: Optional[datetime] = None
    created_date: datetime = None
    
    def __post_init__(self):
        if self.created_date is None:
            self.created_date = datetime.now()

class QualityManagementSystem:
    """质量管理系统核心类"""
    
    def __init__(self):
        self.standards: Dict[str, QualityStandard] = {}
        self.inspection_plans: Dict[str, InspectionPlan] = {}
        self.inspection_records: Dict[str, InspectionRecord] = {}
        self.defect_records: Dict[str, DefectRecord] = {}
        self.ncrs: Dict[str, NCR] = {}
        self.capas: Dict[str, CAPA] = {}
        self.inspectors: Dict[str, Dict] = {}  # 检验员信息
        
    def register_quality_standard(self, standard: QualityStandard) -> bool:
        """注册质量标准"""
        try:
            self.standards[standard.standard_id] = standard
            logger.info(f"质量标准 {standard.name} 注册成功")
            return True
        except Exception as e:
            logger.error(f"质量标准注册失败: {e}")
            return False
    
    def create_inspection_plan(self, plan_data: Dict) -> Optional[str]:
        """创建检验计划"""
        try:
            plan_id = f"IP{datetime.now().strftime('%Y%m%d%H%M%S')}{str(uuid.uuid4())[:6]}"
            
            plan = InspectionPlan(
                plan_id=plan_id,
                product_id=plan_data['product_id'],
                inspection_type=plan_data['inspection_type'],
                standard_id=plan_data['standard_id'],
                frequency=plan_data['frequency'],
                sample_size=plan_data['sample_size'],
                inspector_requirements=plan_data.get('inspector_requirements', []),
                equipment_required=plan_data.get('equipment_required', [])
            )
            
            self.inspection_plans[plan_id] = plan
            logger.info(f"检验计划 {plan_id} 创建成功")
            return plan_id
            
        except Exception as e:
            logger.error(f"创建检验计划失败: {e}")
            return None
    
    def register_inspector(self, inspector_data: Dict) -> bool:
        """注册检验员"""
        try:
            inspector_id = inspector_data['inspector_id']
            self.inspectors[inspector_id] = {
                'name': inspector_data['name'],
                'qualifications': inspector_data.get('qualifications', []),
                'certifications': inspector_data.get('certifications', []),
                'specialties': inspector_data.get('specialties', []),
                'is_active': inspector_data.get('is_active', True)
            }
            logger.info(f"检验员 {inspector_data['name']} 注册成功")
            return True
        except Exception as e:
            logger.error(f"检验员注册失败: {e}")
            return False
    
    def create_inspection_record(self, record_data: Dict) -> Optional[str]:
        """创建检验记录"""
        try:
            record_id = f"IR{datetime.now().strftime('%Y%m%d%H%M%S')}{str(uuid.uuid4())[:6]}"
            
            record = InspectionRecord(
                record_id=record_id,
                plan_id=record_data['plan_id'],
                batch_id=record_data['batch_id'],
                product_id=record_data['product_id'],
                inspection_type=record_data['inspection_type'],
                inspector_id=record_data['inspector_id'],
                inspection_date=record_data.get('inspection_date', datetime.now()),
                sample_size=record_data['sample_size'],
                tested_quantity=record_data['tested_quantity']
            )
            
            self.inspection_records[record_id] = record
            logger.info(f"检验记录 {record_id} 创建成功")
            return record_id
            
        except Exception as e:
            logger.error(f"创建检验记录失败: {e}")
            return None
    
    def update_inspection_result(self, record_id: str, result_data: Dict) -> bool:
        """更新检验结果"""
        if record_id not in self.inspection_records:
            return False
        
        try:
            record = self.inspection_records[record_id]
            
            # 更新检验结果
            if 'result' in result_data:
                record.result = result_data['result']
            
            if 'measurements' in result_data:
                record.measurements.update(result_data['measurements'])
            
            if 'notes' in result_data:
                record.notes = result_data['notes']
            
            if 'completion_date' in result_data:
                record.completion_date = result_data['completion_date']
            else:
                record.completion_date = datetime.now()
            
            # 如果有缺陷数据，创建缺陷记录
            if 'defects' in result_data:
                for defect_data in result_data['defects']:
                    self._create_defect_record(record_id, defect_data)
            
            # 如果检验不合格，自动创建NCR
            if record.result == InspectionResult.FAIL.value:
                self._auto_create_ncr(record_id)
            
            logger.info(f"检验记录 {record_id} 结果更新成功")
            return True
            
        except Exception as e:
            logger.error(f"更新检验结果失败: {e}")
            return False
    
    def _create_defect_record(self, inspection_record_id: str, defect_data: Dict) -> str:
        """创建缺陷记录"""
        defect_id = f"DF{datetime.now().strftime('%Y%m%d%H%M%S')}{str(uuid.uuid4())[:6]}"
        
        defect = DefectRecord(
            defect_id=defect_id,
            inspection_record_id=inspection_record_id,
            defect_type=defect_data['defect_type'],
            defect_description=defect_data['defect_description'],
            severity=defect_data.get('severity', DefectSeverity.MINOR.value),
            quantity=defect_data['quantity'],
            location=defect_data.get('location', ''),
            root_cause=defect_data.get('root_cause', ''),
            corrective_action=defect_data.get('corrective_action', '')
        )
        
        self.defect_records[defect_id] = defect
        
        # 将缺陷记录添加到检验记录中
        if inspection_record_id in self.inspection_records:
            self.inspection_records[inspection_record_id].defects.append({
                'defect_id': defect_id,
                'defect_type': defect_data['defect_type'],
                'quantity': defect_data['quantity'],
                'severity': defect_data.get('severity', DefectSeverity.MINOR.value)
            })
        
        return defect_id
    
    def _auto_create_ncr(self, inspection_record_id: str) -> Optional[str]:
        """自动创建不合格品报告"""
        if inspection_record_id not in self.inspection_records:
            return None
        
        record = self.inspection_records[inspection_record_id]
        
        # 确定严重程度
        severity = DefectSeverity.MINOR.value
        if record.defects:
            severities = [d.get('severity', DefectSeverity.MINOR.value) for d in record.defects]
            if DefectSeverity.CRITICAL.value in severities:
                severity = DefectSeverity.CRITICAL.value
            elif DefectSeverity.MAJOR.value in severities:
                severity = DefectSeverity.MAJOR.value
        
        ncr_data = {
            'inspection_record_id': inspection_record_id,
            'product_id': record.product_id,
            'batch_id': record.batch_id,
            'description': f"检验不合格 - {record.inspection_type}",
            'severity': severity,
            'quantity_affected': record.tested_quantity,
            'reported_by': record.inspector_id
        }
        
        return self.create_ncr(ncr_data)
    
    def create_ncr(self, ncr_data: Dict) -> Optional[str]:
        """创建不合格品报告"""
        try:
            ncr_id = f"NCR{datetime.now().strftime('%Y%m%d%H%M%S')}{str(uuid.uuid4())[:6]}"
            
            ncr = NCR(
                ncr_id=ncr_id,
                inspection_record_id=ncr_data['inspection_record_id'],
                product_id=ncr_data['product_id'],
                batch_id=ncr_data['batch_id'],
                description=ncr_data['description'],
                severity=ncr_data['severity'],
                quantity_affected=ncr_data['quantity_affected'],
                reported_by=ncr_data.get('reported_by', ''),
                assigned_to=ncr_data.get('assigned_to', ''),
                immediate_action=ncr_data.get('immediate_action', ''),
                containment_action=ncr_data.get('containment_action', '')
            )
            
            self.ncrs[ncr_id] = ncr
            logger.info(f"不合格品报告 {ncr_id} 创建成功")
            return ncr_id
            
        except Exception as e:
            logger.error(f"创建不合格品报告失败: {e}")
            return None
    
    def update_ncr_status(self, ncr_id: str, status_data: Dict) -> bool:
        """更新NCR状态"""
        if ncr_id not in self.ncrs:
            return False
        
        try:
            ncr = self.ncrs[ncr_id]
            
            if 'status' in status_data:
                ncr.status = status_data['status']
            
            if 'assigned_to' in status_data:
                ncr.assigned_to = status_data['assigned_to']
            
            if 'root_cause_analysis' in status_data:
                ncr.root_cause_analysis = status_data['root_cause_analysis']
            
            if 'immediate_action' in status_data:
                ncr.immediate_action = status_data['immediate_action']
            
            if 'containment_action' in status_data:
                ncr.containment_action = status_data['containment_action']
            
            if status_data.get('status') == NCRStatus.CLOSED.value:
                ncr.closed_date = datetime.now()
            
            logger.info(f"NCR {ncr_id} 状态更新成功")
            return True
            
        except Exception as e:
            logger.error(f"更新NCR状态失败: {e}")
            return False
    
    def create_capa(self, capa_data: Dict) -> Optional[str]:
        """创建纠正和预防措施"""
        try:
            capa_id = f"CAPA{datetime.now().strftime('%Y%m%d%H%M%S')}{str(uuid.uuid4())[:6]}"
            
            capa = CAPA(
                capa_id=capa_id,
                ncr_id=capa_data['ncr_id'],
                title=capa_data['title'],
                description=capa_data['description'],
                root_cause=capa_data['root_cause'],
                corrective_actions=capa_data.get('corrective_actions', []),
                preventive_actions=capa_data.get('preventive_actions', []),
                responsible_person=capa_data['responsible_person'],
                target_completion_date=capa_data['target_completion_date']
            )
            
            self.capas[capa_id] = capa
            logger.info(f"CAPA {capa_id} 创建成功")
            return capa_id
            
        except Exception as e:
            logger.error(f"创建CAPA失败: {e}")
            return None
    
    def update_capa_status(self, capa_id: str, status_data: Dict) -> bool:
        """更新CAPA状态"""
        if capa_id not in self.capas:
            return False
        
        try:
            capa = self.capas[capa_id]
            
            if 'status' in status_data:
                capa.status = status_data['status']
            
            if 'effectiveness_verification' in status_data:
                capa.effectiveness_verification = status_data['effectiveness_verification']
            
            if status_data.get('status') == CAPAStatus.COMPLETED.value:
                capa.actual_completion_date = datetime.now()
            
            logger.info(f"CAPA {capa_id} 状态更新成功")
            return True
            
        except Exception as e:
            logger.error(f"更新CAPA状态失败: {e}")
            return False
    
    def get_quality_statistics(self, start_date: datetime = None, 
                             end_date: datetime = None) -> Dict:
        """获取质量统计数据"""
        if start_date is None:
            start_date = datetime.now() - timedelta(days=30)
        if end_date is None:
            end_date = datetime.now()
        
        # 筛选时间范围内的检验记录
        period_records = [record for record in self.inspection_records.values() 
                         if start_date <= record.inspection_date <= end_date]
        
        if not period_records:
            return {'message': '指定时间范围内无质量数据'}
        
        # 基本统计
        total_inspections = len(period_records)
        passed_inspections = len([r for r in period_records if r.result == InspectionResult.PASS.value])
        failed_inspections = len([r for r in period_records if r.result == InspectionResult.FAIL.value])
        
        # 合格率
        pass_rate = (passed_inspections / total_inspections * 100) if total_inspections > 0 else 0
        
        # 按检验类型统计
        inspection_type_stats = {}
        for record in period_records:
            inspection_type = record.inspection_type
            if inspection_type not in inspection_type_stats:
                inspection_type_stats[inspection_type] = {
                    'total': 0,
                    'passed': 0,
                    'failed': 0,
                    'pass_rate': 0
                }
            
            inspection_type_stats[inspection_type]['total'] += 1
            if record.result == InspectionResult.PASS.value:
                inspection_type_stats[inspection_type]['passed'] += 1
            elif record.result == InspectionResult.FAIL.value:
                inspection_type_stats[inspection_type]['failed'] += 1
        
        # 计算各类型合格率
        for type_name, stats in inspection_type_stats.items():
            if stats['total'] > 0:
                stats['pass_rate'] = round(stats['passed'] / stats['total'] * 100, 2)
        
        # 缺陷分析
        period_defects = [defect for defect in self.defect_records.values() 
                         if defect.created_date and start_date <= defect.created_date <= end_date]
        
        defect_type_distribution = {}
        defect_severity_distribution = {}
        
        for defect in period_defects:
            # 按类型统计
            defect_type = defect.defect_type
            defect_type_distribution[defect_type] = defect_type_distribution.get(defect_type, 0) + defect.quantity
            
            # 按严重程度统计
            severity = defect.severity
            defect_severity_distribution[severity] = defect_severity_distribution.get(severity, 0) + defect.quantity
        
        # NCR统计
        period_ncrs = [ncr for ncr in self.ncrs.values() 
                      if start_date <= ncr.created_date <= end_date]
        
        ncr_stats = {
            'total_ncrs': len(period_ncrs),
            'open_ncrs': len([n for n in period_ncrs if n.status == NCRStatus.OPEN.value]),
            'closed_ncrs': len([n for n in period_ncrs if n.status == NCRStatus.CLOSED.value]),
            'average_closure_time': 0
        }
        
        # 计算平均关闭时间
        closed_ncrs = [n for n in period_ncrs if n.status == NCRStatus.CLOSED.value and n.closed_date]
        if closed_ncrs:
            total_closure_time = sum(
                (n.closed_date - n.created_date).total_seconds() / 3600 
                for n in closed_ncrs
            )
            ncr_stats['average_closure_time'] = round(total_closure_time / len(closed_ncrs), 2)
        
        # CAPA统计
        period_capas = [capa for capa in self.capas.values() 
                       if start_date <= capa.created_date <= end_date]
        
        capa_stats = {
            'total_capas': len(period_capas),
            'completed_capas': len([c for c in period_capas if c.status == CAPAStatus.COMPLETED.value]),
            'overdue_capas': len([c for c in period_capas 
                                if c.target_completion_date < datetime.now() and 
                                c.status != CAPAStatus.COMPLETED.value])
        }
        
        return {
            'period': {
                'start_date': start_date.isoformat(),
                'end_date': end_date.isoformat()
            },
            'inspection_summary': {
                'total_inspections': total_inspections,
                'passed_inspections': passed_inspections,
                'failed_inspections': failed_inspections,
                'overall_pass_rate': round(pass_rate, 2)
            },
            'inspection_type_statistics': inspection_type_stats,
            'defect_analysis': {
                'total_defects': sum(defect_type_distribution.values()),
                'defect_type_distribution': defect_type_distribution,
                'defect_severity_distribution': defect_severity_distribution
            },
            'ncr_statistics': ncr_stats,
            'capa_statistics': capa_stats
        }
    
    def get_quality_trends(self, days: int = 30) -> Dict:
        """获取质量趋势分析"""
        end_date = datetime.now()
        start_date = end_date - timedelta(days=days)
        
        # 按日期分组统计
        daily_stats = {}
        
        for i in range(days):
            date = start_date + timedelta(days=i)
            date_str = date.strftime('%Y-%m-%d')
            
            # 当日检验记录
            daily_records = [record for record in self.inspection_records.values() 
                           if record.inspection_date.date() == date.date()]
            
            daily_stats[date_str] = {
                'total_inspections': len(daily_records),
                'passed_inspections': len([r for r in daily_records if r.result == InspectionResult.PASS.value]),
                'failed_inspections': len([r for r in daily_records if r.result == InspectionResult.FAIL.value]),
                'pass_rate': 0
            }
            
            if daily_stats[date_str]['total_inspections'] > 0:
                daily_stats[date_str]['pass_rate'] = round(
                    daily_stats[date_str]['passed_inspections'] / daily_stats[date_str]['total_inspections'] * 100, 2
                )
        
        # 计算趋势
        pass_rates = [stats['pass_rate'] for stats in daily_stats.values() if stats['total_inspections'] > 0]
        
        trend_analysis = {
            'average_pass_rate': round(statistics.mean(pass_rates), 2) if pass_rates else 0,
            'pass_rate_std': round(statistics.stdev(pass_rates), 2) if len(pass_rates) > 1 else 0,
            'trend_direction': 'stable'
        }
        
        # 简单趋势分析
        if len(pass_rates) >= 7:
            recent_avg = statistics.mean(pass_rates[-7:])
            earlier_avg = statistics.mean(pass_rates[:7])
            
            if recent_avg > earlier_avg + 2:
                trend_analysis['trend_direction'] = 'improving'
            elif recent_avg < earlier_avg - 2:
                trend_analysis['trend_direction'] = 'declining'
        
        return {
            'period': {
                'start_date': start_date.isoformat(),
                'end_date': end_date.isoformat(),
                'days': days
            },
            'daily_statistics': daily_stats,
            'trend_analysis': trend_analysis
        }
    
    def get_improvement_recommendations(self) -> List[Dict]:
        """获取质量改进建议"""
        recommendations = []
        
        # 分析最近30天的数据
        recent_stats = self.get_quality_statistics(datetime.now() - timedelta(days=30))
        
        if 'message' in recent_stats:
            return [{'type': 'info', 'message': '数据不足，无法生成改进建议'}]
        
        # 基于合格率的建议
        overall_pass_rate = recent_stats['inspection_summary']['overall_pass_rate']
        if overall_pass_rate < 95:
            recommendations.append({
                'type': 'quality_improvement',
                'priority': 'high',
                'title': '整体合格率偏低',
                'description': f'当前整体合格率为 {overall_pass_rate}%，建议加强质量控制',
                'suggested_actions': [
                    '审查和更新质量标准',
                    '加强检验员培训',
                    '改进生产工艺',
                    '增加过程检验频率'
                ]
            })
        
        # 基于缺陷分析的建议
        defect_analysis = recent_stats['defect_analysis']
        if defect_analysis['total_defects'] > 0:
            # 找出最常见的缺陷类型
            most_common_defect = max(defect_analysis['defect_type_distribution'].items(), 
                                   key=lambda x: x[1])
            
            recommendations.append({
                'type': 'defect_reduction',
                'priority': 'medium',
                'title': f'重点关注 {most_common_defect[0]} 缺陷',
                'description': f'{most_common_defect[0]} 是最常见的缺陷类型，占总缺陷的 {most_common_defect[1]} 个',
                'suggested_actions': [
                    f'针对 {most_common_defect[0]} 进行根因分析',
                    '制定专项改进计划',
                    '加强相关工序的监控',
                    '更新作业指导书'
                ]
            })
        
        # 基于NCR统计的建议
        ncr_stats = recent_stats['ncr_statistics']
        if ncr_stats['open_ncrs'] > ncr_stats['closed_ncrs']:
            recommendations.append({
                'type': 'process_improvement',
                'priority': 'medium',
                'title': 'NCR处理效率需要提升',
                'description': f'当前有 {ncr_stats["open_ncrs"]} 个未关闭的NCR，处理效率有待提高',
                'suggested_actions': [
                    '建立NCR处理时限要求',
                    '指定专人跟踪NCR处理进度',
                    '定期召开NCR评审会议',
                    '优化NCR处理流程'
                ]
            })
        
        # 基于CAPA统计的建议
        capa_stats = recent_stats['capa_statistics']
        if capa_stats['overdue_capas'] > 0:
            recommendations.append({
                'type': 'capa_management',
                'priority': 'high',
                'title': 'CAPA执行进度滞后',
                'description': f'有 {capa_stats["overdue_capas"]} 个CAPA超期未完成',
                'suggested_actions': [
                    '重新评估CAPA完成时间',
                    '增加资源投入',
                    '建立CAPA进度跟踪机制',
                    '定期评审CAPA有效性'
                ]
            })
        
        # 基于检验类型的建议
        type_stats = recent_stats['inspection_type_statistics']
        for inspection_type, stats in type_stats.items():
            if stats['pass_rate'] < 90:
                recommendations.append({
                    'type': 'inspection_improvement',
                    'priority': 'medium',
                    'title': f'{inspection_type} 检验合格率偏低',
                    'description': f'{inspection_type} 检验合格率为 {stats["pass_rate"]}%，需要重点关注',
                    'suggested_actions': [
                        f'分析 {inspection_type} 检验失败的主要原因',
                        '优化检验方法和标准',
                        '加强相关环节的质量控制',
                        '提高检验员专业技能'
                    ]
                })
        
        # 如果没有发现问题，给出积极建议
        if not recommendations:
            recommendations.append({
                'type': 'continuous_improvement',
                'priority': 'low',
                'title': '质量表现良好',
                'description': '当前质量指标表现良好，建议继续保持并寻求进一步改进',
                'suggested_actions': [
                    '建立质量标杆管理',
                    '推广最佳实践',
                    '持续优化质量流程',
                    '开展质量创新活动'
                ]
            })
        
        return recommendations
    
    def export_quality_data(self, file_path: str, data_type: str = "inspections") -> bool:
        """导出质量数据"""
        try:
            if data_type == "inspections":
                data = []
                for record in self.inspection_records.values():
                    record_data = asdict(record)
                    # 转换datetime对象为字符串
                    for key, value in record_data.items():
                        if isinstance(value, datetime):
                            record_data[key] = value.isoformat()
                    data.append(record_data)
            
            elif data_type == "defects":
                data = []
                for defect in self.defect_records.values():
                    defect_data = asdict(defect)
                    for key, value in defect_data.items():
                        if isinstance(value, datetime):
                            defect_data[key] = value.isoformat()
                    data.append(defect_data)
            
            elif data_type == "ncrs":
                data = []
                for ncr in self.ncrs.values():
                    ncr_data = asdict(ncr)
                    for key, value in ncr_data.items():
                        if isinstance(value, datetime):
                            ncr_data[key] = value.isoformat()
                    data.append(ncr_data)
            
            elif data_type == "capas":
                data = []
                for capa in self.capas.values():
                    capa_data = asdict(capa)
                    for key, value in capa_data.items():
                        if isinstance(value, datetime):
                            capa_data[key] = value.isoformat()
                    data.append(capa_data)
            
            else:
                logger.error(f"不支持的数据类型: {data_type}")
                return False
            
            df = pd.DataFrame(data)
            df.to_csv(file_path, index=False, encoding='utf-8-sig')
            logger.info(f"{data_type} 数据已导出到 {file_path}")
            return True
            
        except Exception as e:
            logger.error(f"导出数据失败: {e}")
            return False

# 示例使用
if __name__ == "__main__":
    # 创建质量管理系统实例
    qms = QualityManagementSystem()
    
    # 注册质量标准
    standard = QualityStandard(
        standard_id="STD001",
        name="电子产品外观检验标准",
        category="外观检验",
        description="电子产品外观质量检验标准",
        acceptance_criteria={
            "表面划痕": "无可见划痕",
            "颜色一致性": "色差ΔE<2",
            "装配间隙": "<0.2mm"
        },
        test_methods=["目视检验", "色差仪测量", "间隙规测量"],
        sampling_plan={"抽样方式": "随机抽样", "抽样比例": "5%"}
    )
    qms.register_quality_standard(standard)
    
    # 注册检验员
    inspector_data = {
        'inspector_id': 'INS001',
        'name': '张检验',
        'qualifications': ['质量工程师'],
        'certifications': ['ISO9001内审员'],
        'specialties': ['外观检验', '尺寸测量']
    }
    qms.register_inspector(inspector_data)
    
    # 创建检验计划
    plan_data = {
        'product_id': 'PROD001',
        'inspection_type': InspectionType.FINAL.value,
        'standard_id': 'STD001',
        'frequency': '每批次',
        'sample_size': 10,
        'inspector_requirements': ['外观检验资质'],
        'equipment_required': ['色差仪', '间隙规']
    }
    
    plan_id = qms.create_inspection_plan(plan_data)
    if plan_id:
        print(f"检验计划创建成功: {plan_id}")
        
        # 创建检验记录
        record_data = {
            'plan_id': plan_id,
            'batch_id': 'BATCH001',
            'product_id': 'PROD001',
            'inspection_type': InspectionType.FINAL.value,
            'inspector_id': 'INS001',
            'sample_size': 10,
            'tested_quantity': 10
        }
        
        record_id = qms.create_inspection_record(record_data)
        print(f"检验记录创建成功: {record_id}")
        
        # 更新检验结果
        result_data = {
            'result': InspectionResult.FAIL.value,
            'measurements': {'色差': 2.5, '间隙': 0.15},
            'notes': '发现外观缺陷',
            'defects': [{
                'defect_type': '表面划痕',
                'defect_description': '产品表面有明显划痕',
                'severity': DefectSeverity.MAJOR.value,
                'quantity': 2,
                'location': '前面板'
            }]
        }
        
        qms.update_inspection_result(record_id, result_data)
        
        # 获取质量统计
        quality_stats = qms.get_quality_statistics()
        print("质量统计:", json.dumps(quality_stats, indent=2, default=str, ensure_ascii=False))
        
        # 获取改进建议
        recommendations = qms.get_improvement_recommendations()
        print("改进建议:", json.dumps(recommendations, indent=2, default=str, ensure_ascii=False))